import React, { useEffect, useState } from 'react';
import { Card, Table, Form, DatePicker, Input, Button, Row, Col, Select } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { getOperationLog, getOperationLogModule } from 'admin/servers/modules/Cas';
import { OperationLogItem } from 'admin/schema/Cas';
import { map } from 'lodash';

const { RangePicker } = DatePicker;

const OperationLog: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<OperationLogItem[]>([]);
  const [modules, setModules] = useState<string[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [form] = Form.useForm();

  const columns: ColumnsType<OperationLogItem> = [
    {
      title: '操作模块',
      dataIndex: 'operModule',
      key: 'operModule',
    },
    {
      title: '操作用户',
      dataIndex: 'operUser',
      key: 'operUser',
    },
    {
      title: '操作IP',
      dataIndex: 'operIp',
      key: 'operIp',
    },
    {
      title: '操作时间',
      dataIndex: 'operTime',
      key: 'operTime',
    },
    {
      title: '耗时',
      dataIndex: 'costTime',
      key: 'costTime',
    },
    {
      title: '操作描述',
      dataIndex: 'operDesc',
      key: 'operDesc',
      width: '30%',
      ellipsis: true,
    },
  ];

  const fetchData = async (page = pagination.current, pageSize = pagination.pageSize) => {
    setLoading(true);
    try {
      const values = form.getFieldsValue();
      const timeRange = values.dateRange
        ? [
            values.dateRange[0].startOf('day').format('YYYY-MM-DD HH:mm:ss'),
            values.dateRange[1].endOf('day').format('YYYY-MM-DD HH:mm:ss'),
          ]
        : [];

      const response = await getOperationLog(
        page,
        pageSize,
        values.ip,
        values.desc,
        timeRange[0],
        timeRange[1],
        values.operUser,
        values.operModule
      );

      setData(response.data.data);
      setPagination({
        ...pagination,
        current: page,
        total: response.data.totalRecords,
      });
    } catch (error) {
      console.error('获取操作日志失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchModules = async () => {
    try {
      const response = await getOperationLogModule();
      if (response.status === '200') {
        setModules(map(response.data, 'type'));
      }
    } catch (error) {
      console.error('获取操作模块列表失败:', error);
    }
  };

  useEffect(() => {
    fetchData();
    fetchModules();
    // eslint-disable-next-line
  }, []);

  const handleTableChange = (pagination: any) => {
    fetchData(pagination.current, pagination.pageSize);
  };

  const handleSearch = async () => {
    fetchData(1);
  };

  const handleReset = () => {
    form.resetFields();
    fetchData(1);
  };

  return (
    <Card>
      <Form form={form} layout="inline" style={{ marginBottom: 16 }}>
        <Row gutter={[16, 8]} style={{ width: '100%' }}>
          <Col span={6}>
            <Form.Item name="operUser" label="操作用户">
              <Input placeholder="请输入操作用户" allowClear />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="ip" label="操作IP">
              <Input placeholder="请输入操作IP" allowClear />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item name="dateRange" label="操作时间">
              <RangePicker />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="operModule" label="操作模块">
              <Select placeholder="请选择操作模块">
                {map(modules, module => (
                  <Select.Option key={module} value={module}>
                    {module}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          {/* <Col span={6}>
            <Form.Item name="desc" label="操作描述">
              <Input placeholder="请输入操作描述" allowClear />
            </Form.Item>
          </Col> */}
          <Col span={4}>
            <Form.Item>
              <Button type="primary" onClick={handleSearch} style={{ marginRight: 8 }}>
                查询
              </Button>
              <Button onClick={handleReset}>重置</Button>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <Table
        columns={columns}
        dataSource={data}
        pagination={pagination}
        loading={loading}
        onChange={handleTableChange}
      />
    </Card>
  );
};

export default OperationLog;
